<?php

namespace addons\mental\model;;

use think\Model;
use traits\model\SoftDelete;

class Testlog extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'mental_testlog';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'question_time',
        'testreportData2',
        'testreportData1',
        'evaluationStructure',
        'imgarr',
    ];

    protected static function init()
    {
        self::event('before_insert', function ($model) {
            $model->testNo = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(1000, 9999);
        });



        self::event('before_update', function ($model) {



            $dimensionRule = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionRule'); //维度配置规则


            if (in_array($dimensionRule, [1, 2, 3, 5, 6,7,8,9,10,11])) {
                $model = self::getRule($model);
                if ($dimensionRule == 3) {
                    $model = self::getRule1($model);
                } elseif ($dimensionRule == 2) {
                    $model = self::getRule2($model);
                }elseif ($dimensionRule == 5) {
                    $model = self::getRule5($model);
                } elseif ($dimensionRule == 6) {
                    $model = self::getRule6($model);
                } elseif ($dimensionRule ==7) {
                    $model = self::getRule7($model);
                } elseif ($dimensionRule == 8) {
                    $model = self::getRule8($model);
                } elseif ($dimensionRule == 9) {
                    $model = self::getRule9($model);
                } elseif ($dimensionRule == 10) {
                    $model = self::getRule10($model);
                } elseif ($dimensionRule == 11) {
                    $model = self::getRule11($model);
                }
            } elseif ($dimensionRule == 4) {
                $model = self::getRule4($model);
            }
            // var_dump($model);die;

        });
    }



    public static function getRule4($model)
    {
        $resultStr = '';
        $extends1 = [
            'F1' => 0,
            'F2' => 0,
            'F3' => 0,
            'F4' => 0,
            'F5' => 0,
            'F6' => 0,
            'F7' => 0,
            'F8' => 0,
            'F9' => 0,
            'F10' => 0
        ];
        $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');
        $dimensionArr = json_decode($dimensionArr);
        $result_arr = json_decode(html_entity_decode($model['result_log']), true);

        $testson = new Testson();
        $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);


        $extendsArr = [];
        $positiveNum = 0; //阳性项目总数
        $negativeNum = 0; //阴性项目总数

        $positiveTotalS = 0; //阳性项目总分
        $negativeTotalS = 0; //阴性项目总分

        $result_arr = json_decode(html_entity_decode($model['result_log']), true);

        foreach ($result_arr as $k => $v) {
            $question = Question::getById($v['question_id'])->toArray();

            foreach ($question['question'] as $kk => $vv) {
                if ($vv['option'] == $v['userAnswer']) {
                    $positiveNum += $vv['option'] == 'A' ? 1 : 0; //阳性项目总数
                    $negativeNum += $vv['option'] !== 'A' ? 1 : 0; //阴性项目总数
                    $positiveTotalS += $vv['option'] == 'A' ? $vv['score'] : 0; //阳性项目总分
                    $negativeTotalS += $vv['option'] !== 'A' ? $vv['score'] : 0; //阴性项目总分

                    if (array_key_exists($vv['dimension'], $extendsArr)) {
                        $extendsArr[$vv['dimension']]['S'] += $vv['score']; //累计得分
                        $extendsArr[$vv['dimension']]['num'] += 1; //项目总数
                        $extendsArr[$vv['dimension']]['positiveNum'] += $vv['option'] == 'A' ? 1 : 0; //阳性项目数
                        $extendsArr[$vv['dimension']]['negativeNum'] += $vv['option'] !== 'A' ? 1 : 0; //阴性项目数
                        $extendsArr[$vv['dimension']]['positiveS'] += $vv['option'] == 'A' ? $vv['score'] : 0; //阳性项目分
                        $extendsArr[$vv['dimension']]['negativeS'] += $vv['option'] !== 'A' ? $vv['score'] : 0; //阴性项目分
                    } else {
                        $extendsArr[$vv['dimension']] = [
                            'S' => $vv['score'],
                            'num' => 1, //项目总数
                            'positiveNum' => $vv['option'] == 'A' ? 1 : 0, //阳性项目数
                            'negativeNum' => $vv['option'] !== 'A' ? 1 : 0, //阴性项目数
                            'positiveS' => $vv['option'] == 'A' ? $vv['score'] : 0, //阳性项目分
                            'negativeS' => $vv['option'] !== 'A' ? $vv['score'] : 0, //阴性项目分
                        ];
                    }
                    $result_arr[$k]['S'] = $vv['score'];
                }
            }
        }
        $totalS = 0; //总累计得分
        $totalT = 0; //总因子分
        foreach ($extendsArr as $k => $v) {
            $T = $v['S'] / $v['num'];
            $extendsArr[$k]['T'] = $T; //因子分
            $totalS += $v['S'];
            $totalT += $T;
        }

        $questionsNum = Question::where('main_id', $model['main_id'])->count(); //总问题数

        $ruleConfig = json_decode(TestMain::where('id', $model['main_id'])->value('ruleConfig'), true);

        $ruleConfig['totalScore']['totalS'] = $totalS; //总分数
        $ruleConfig['totalT'] = $totalT; //总因子分
        $ruleConfig['totalAverageScore']['totalAverageS'] = $totalS / $questionsNum; //总均分
        $ruleConfig['questionsNum'] = $questionsNum; //总问题数

        $ruleConfig['positive']['num'] = $positiveNum; //阳性项目总数
        $ruleConfig['negative']['num'] = $negativeNum; //阴性项目总数
        $ruleConfig['yxzzjf']['totalAverageS'] = $positiveTotalS / $questionsNum; //阴性项目总数

        foreach ($ruleConfig['yzf'] as $k => $v) {
            $arr = $extendsArr[$k];
            if (empty($v['s1']) || empty($v['s2'])) {
                $arr['status'] = 1;
                $arr['statusStr'] = '正常';
            } else {
                $a1 = $v['s1'] + $v['s2'];
                $a2 = $v['s1'] - $v['s2'];

                $arr['status'] = $a1 > $arr['T'] && $a2 < $arr['T'] ? 1 : 0;
                $arr['statusStr'] = $a1 > $arr['T'] && $a2 < $arr['T'] ? '正常' : '异常';
            }
            $arr['s1'] = $a1;
            $arr['s2'] = $a2;
            $ruleConfig['yzf'][$k] = $arr;
        }

        foreach ($extends1 as $k => $v) {
            foreach ($getDimension as $kk => $vv) {
                if (strstr($k, $vv['key'])) {
                    $extends1[$k] += $vv['score'];
                }
            }
        }
        $exArr = [];
        $score = 0;
        foreach ($extends1 as $k => $v) {
            $exArr[] = [
                'str' => $k,
                'score' => $v,
            ];
            if($v>$score){
                $score = $v;
                $resultStr = $k;
            }
        }
        $idArr = array_column($exArr, 'score');

        array_multisort($idArr, SORT_DESC, $exArr);

        $model->extends = json_encode($ruleConfig);
        $model->extends1 = json_encode($exArr);
        $model->dimensionArr = json_encode($getDimension);
        $model->resultStr = $resultStr;
        return $model;
    }


    // public static function getRule4($model)
    // {

    //     // var_dump($model);die;
    //     $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');
    //     $dimensionArr = json_decode($dimensionArr);
    //     $result_arr = json_decode(html_entity_decode($model['result_log']), true);

    //     $testson = new Testson();
    //     $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);
    //     $totalScore = $testson->totalScore($model['main_id'], $result_arr);//统计分数

    //     $getDimension1 = $getDimension;

    //     foreach ($getDimension1 as $k => $v) {
    //         $getDimension1[$k]['proportion'] = round($v['score'] / $totalScore * 100, 2);
    //     }





    //     $highestScoreArr1 = [];
    //     for ($i = 0; $i < 3; $i++) {
    //         $highestScoreArr = null; //最高分数组
    //         $highestScoreKey = '';
    //         $highestScore = 0;
    //         foreach ($getDimension as $k => $v) {
    //             $getDimension[$k]['proportion'] = round($v['score'] / $totalScore * 100, 2);
    //             if ($v['score'] > $highestScore) {
    //                 $v['proportion'] = round($v['score'] / $totalScore * 100, 2);
    //                 $highestScoreArr = $v;
    //                 $highestScore = $v['score'];
    //                 $highestScoreKey = $k;
    //             }
    //         }

    //         $highestScoreArr1[$i] = $highestScoreArr;
    //         unset($getDimension[$highestScoreKey]);
    //     }
    //     $resultStr = $highestScoreArr1[0]['key'];

    //     $model->dimensionArr = json_encode($getDimension1);
    //     $model->total_score = $totalScore;
    //     $model->extends  = json_encode([]);
    //     $model->extends1 = json_encode($highestScoreArr1);
    //     $model->resultStr = $resultStr;
    //     // var_dump($getDimension1);die;
    //     return $model;

    // }







    /**
     * MBTI计算规则&&维度最高分计算规则
     */
    public static function getRule($model)
    {
        $resultStr = '';
        $extends = [];
        //MBTI职业性格测试学生版
        if($model['main_id']==5 || $model['main_id']==1 || $model['main_id']==4){   
            $extends1 = [
                'E' => 0,
                'P' => 0,
                'T' => 0,
                'N' => 0,
                'I' => 0,
                'J' => 0,
                'F' => 0,
                'S' => 0,
            ];
        }else{
            $extends1 = [
                'SJ' => 0,
                'NF' => 0,
                'SP' => 0,
                'NT' => 0,
            ];
        }

        $result_arr = json_decode(html_entity_decode($model['result_log']), true);
        $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');

        $dimensionRule = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionRule'); //维度配置规则
        $dimensionArr = json_decode($dimensionArr);
        //去统计分数
        $testson = new Testson();
        $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);
        $totalScore = $testson->totalScore($model['main_id'], $result_arr); //统计分数
        $highestScoreArr = []; //最高分数组
        $highestScore = 0;
        // var_dump($getDimension);die;
        foreach ($getDimension as $k => $v) {
            $getDimension[$k]['proportion'] = round($v['score'] / $totalScore * 100, 2);


            if ($v['score'] > $highestScore) {
                $highestScoreArr = $v;
                $highestScore = $v['score'];
            }
        }
//        halt($getDimension);
        $getDimensionCount = count($getDimension);
        $isdc = $getDimensionCount % 2;
        if ($isdc == 0) {

            $icount = $getDimensionCount / 2;
            $icount1 = $icount;
            $kke = 5;
            $resultStrArr = [];
            for ($i = 0; $i < $icount; $i++) {
                $a = $getDimension[$i];
                $a1 = $getDimension[$icount1];
                $isdd = true;
                if ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $isdd = false;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    //  $extends[4] = [$a1,$a];
//                    $resultStrArr[4] = $resultStr1;
                    $isdd = false;
                }
                if ($a['score'] > $a1['score']) {
                    $resultStr1 = $a['key'];
                    $a['large'] = true;
                    $a1['large'] = false;
                } elseif ($a['score'] == $a1['score']) {
                    if ($isdd) {
                        $resultStr1 = $a1['key'];
                        $a['large'] = false;
                        $a1['large'] = true;
                    } else {
                        $resultStr1 = $a['key'];
                        $a['large'] = true;
                        $a1['large'] = false;
                    }
                } else {
                    $resultStr1 = $a1['key'];
                    $a['large'] = false;
                    $a1['large'] = true;
                }

                if ($a['key'] == 'E' || $a1['key'] == 'E') {
                    $extends[1] = [$a, $a1];
                    $resultStrArr[1] = $resultStr1;
                } elseif ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $extends[2] = [$a1, $a];
                    $resultStrArr[2] = $resultStr1;
                    //  $isdd = false;
                } elseif ($a['key'] == 'T' || $a1['key'] == 'T') {
                    $extends[3] = [$a, $a1];
                    $resultStrArr[3] = $resultStr1;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    $extends[4] = [$a1, $a];
                    $resultStrArr[4] = $resultStr1;
                    //  $isdd = false;
                } else {
                    $extends[$kke] = [$a, $a1];
                    $kke++;
                }


                $icount1++;
            }

            if ($dimensionRule == 1) {
                ksort($resultStrArr);
                $resultStr = implode($resultStrArr);
            } elseif ($dimensionRule == 2) {
                $resultStr = $highestScoreArr['key'];
            }
        }


        foreach ($extends1 as $k => $v) {
            foreach ($getDimension as $kk => $vv) {
                if (strstr($k, $vv['key'])) {
                    $extends1[$k] += $vv['score'];
                }
            }
        }


        $exArr = [];
        // rsort($extends1);
        $score = 0;
        foreach ($extends1 as $k => $v) {
            $exArr[] = [
                'str' => $k,
                'score' => $v,
            ];
            if($model['main_id']==5 || $model['main_id']==1 || $model['main_id']==4){                
                if($v>$score){
                    $score = $v;
                    $resultStr = $k;
                }
            }
        }
        // var_dump($exArr);die;
        $idArr = array_column($exArr, 'score');

        array_multisort($idArr, SORT_DESC, $exArr);


        $invitation_code = $model['invitation_code'];
        if ($invitation_code) {
            if ($model['status'] == "finish") {
                \think\Db::name('mental_invitationcode')->where(['invitation_code' => $invitation_code])->setInc('used_num');
            }
        }

        $model->dimensionArr = json_encode($getDimension);
        $model->total_score = $totalScore;
        $model->extends  = json_encode($extends);
        $model->extends1 = json_encode($exArr);
        $model->resultStr = $resultStr;



        return $model;
    }



    /**
     * 人格七宗罪  2  
     */
    public static function getRule2($model)
    {
        $resultStr = '';
        $extends = [];
        
        // 霍兰德职业兴趣测试 
        if($model['main_id']==2){  
            $extends1 = [
                'R' => 0,
                'I' => 0,
                'A' => 0,
                'S' => 0,
                'E' => 0,
                'C' => 0,
            ];
        }

        // 霍兰德职业兴趣测试学生版
        if($model['main_id']==6){            
            $extends1 = [
                'S' => 0,
                'E' => 0,
                'C' => 0,
                'R' => 0,
                'A' => 0,
                'I' => 0,
            ];
        }

        // 人格七宗罪
        if($model['main_id']==7){            
            $extends1 = [
                'A' => 0,
                'B' => 0,
                'C' => 0,
                'D' => 0,
                'E' => 0,
                'F' => 0,
                'G' => 0,
            ];
        }

        // 荣格性格测试-速测版
        if($model['main_id']==13){  
            $extends1 = [
                'Te' => 0,
                'Ti' => 0,
                'Fe' => 0,
                'Fi' => 0,
                'Se' => 0,
                'Si' => 0,
                'Ne' => 0,
                'Ni' => 0,
            ];
        }

        // MIDAS多元智能测评
        if($model['main_id']==20){  
            $extends1 = [
                'A' => 0,
                'B' => 0,
                'C' => 0,
                'D' => 0,
                'E' => 0,
                'F' => 0,
                'G' => 0,
                'H' => 0,
            ];
        }



        $result_arr = json_decode(html_entity_decode($model['result_log']), true);
        $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');

        $dimensionRule = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionRule'); //维度配置规则
        $dimensionArr = json_decode($dimensionArr);
        //去统计分数
        $testson = new Testson();
        $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);
        $totalScore = $testson->totalScore($model['main_id'], $result_arr); //统计分数
        $highestScoreArr = []; //最高分数组
        $highestScore = 0;
        // var_dump($getDimension);die;
        foreach ($getDimension as $k => $v) {
            $getDimension[$k]['proportion'] = round($v['score'] / $totalScore * 100, 2);
            if ($v['score'] > $highestScore) {
                $highestScoreArr = $v;
                $highestScore = $v['score'];
            }
        }
        $getDimensionCount = count($getDimension);
        $isdc = $getDimensionCount % 2;
        if ($isdc == 0) {

            $icount = $getDimensionCount / 2;
            $icount1 = $icount;
            $kke = 5;
            $resultStrArr = [];
            for ($i = 0; $i < $icount; $i++) {
                $a = $getDimension[$i];
                $a1 = $getDimension[$icount1];
                $isdd = true;
                if ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $isdd = false;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    //  $extends[4] = [$a1,$a];
//                    $resultStrArr[4] = $resultStr1;
                    $isdd = false;
                }
                if ($a['score'] > $a1['score']) {
                    $resultStr1 = $a['key'];
                    $a['large'] = true;
                    $a1['large'] = false;
                } elseif ($a['score'] == $a1['score']) {
                    if ($isdd) {
                        $resultStr1 = $a1['key'];
                        $a['large'] = false;
                        $a1['large'] = true;
                    } else {
                        $resultStr1 = $a['key'];
                        $a['large'] = true;
                        $a1['large'] = false;
                    }
                } else {
                    $resultStr1 = $a1['key'];
                    $a['large'] = false;
                    $a1['large'] = true;
                }

                if ($a['key'] == 'E' || $a1['key'] == 'E') {
                    $extends[1] = [$a, $a1];
                    $resultStrArr[1] = $resultStr1;
                } elseif ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $extends[2] = [$a1, $a];
                    $resultStrArr[2] = $resultStr1;
                    //  $isdd = false;
                } elseif ($a['key'] == 'T' || $a1['key'] == 'T') {
                    $extends[3] = [$a, $a1];
                    $resultStrArr[3] = $resultStr1;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    $extends[4] = [$a1, $a];
                    $resultStrArr[4] = $resultStr1;
                    //  $isdd = false;
                } else {
                    $extends[$kke] = [$a, $a1];
                    $kke++;
                }


                $icount1++;
            }

            if ($dimensionRule == 1) {
                ksort($resultStrArr);
                $resultStr = implode($resultStrArr);
            } elseif ($dimensionRule == 2) {
                $resultStr = $highestScoreArr['key'];
            }
        }


        foreach ($extends1 as $k => $v) {
            foreach ($getDimension as $kk => $vv) {
                if (strstr($k, $vv['key'])) {
                    $extends1[$k] += $vv['score'];
                }
            }
        }


        $exArr = [];
        $score = 0;
        foreach ($extends1 as $k => $v) {
            $exArr[] = [
                'str' => $k,
                'score' => $v,
            ];
            if($v>$score){
                $score = $v;
                $resultStr = $k;
            }
        }
        $idArr = array_column($exArr, 'score');

        array_multisort($idArr, SORT_DESC, $exArr);


        $invitation_code = $model['invitation_code'];
        if ($invitation_code) {
            if ($model['status'] == "finish") {
                \think\Db::name('mental_invitationcode')->where(['invitation_code' => $invitation_code])->setInc('used_num');
            }
        }
        $model->dimensionArr = json_encode($getDimension);
        $model->total_score = $totalScore;
        $model->extends  = json_encode($extends);
        $model->extends1 = json_encode($exArr);
        $model->resultStr = $resultStr;



        return $model;
    }



    /**
     * MBTI性格计算规则
     */
    public static function getRule8($model)
    {
        $resultStr = '';
        $extends = [];
        $extends1 = [
            'SJ' => 0,
            'NF' => 0,
            'SP' => 0,
            'NT' => 0,
        ];
//        halt($extends1);
        $result_arr = json_decode(html_entity_decode($model['result_log']), true);
        $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');

        $dimensionRule = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionRule'); //维度配置规则
        $dimensionArr = json_decode($dimensionArr);
        //去统计分数
        $testson = new Testson();
        $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);
        $totalScore = $testson->totalScore($model['main_id'], $result_arr); //统计分数
        $highestScoreArr = []; //最高分数组
        $highestScore = 0;
        // var_dump($getDimension);die;
        foreach ($getDimension as $k => $v) {
            $getDimension[$k]['proportion'] = round($v['score'] / $totalScore * 100, 2);


            if ($v['score'] > $highestScore) {
                $highestScoreArr = $v;
                $highestScore = $v['score'];
            }
        }

        $getDimensionCount = count($getDimension);
        $isdc = $getDimensionCount % 2;
        if ($isdc == 0) {

            $icount = $getDimensionCount / 2;
            $icount1 = $icount;
            $kke = 5;
            $resultStrArr = [];
            for ($i = 0; $i < $icount; $i++) {
                $a = $getDimension[$i];
                $a1 = $getDimension[$icount1];
                $isdd = true;
                if ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $isdd = false;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    //  $extends[4] = [$a1,$a];
//                    $resultStrArr[4] = $resultStr1;
                    $isdd = false;
                }
                if ($a['score'] > $a1['score']) {
                    $resultStr1 = $a['key'];
                    $a['large'] = true;
                    $a1['large'] = false;
                } elseif ($a['score'] == $a1['score']) {
                    if ($isdd) {
                        $resultStr1 = $a1['key'];
                        $a['large'] = false;
                        $a1['large'] = true;
                    } else {
                        $resultStr1 = $a['key'];
                        $a['large'] = true;
                        $a1['large'] = false;
                    }
                } else {
                    $resultStr1 = $a1['key'];
                    $a['large'] = false;
                    $a1['large'] = true;
                }

                if ($a['key'] == 'E' || $a1['key'] == 'E') {
                    $extends[1] = [$a, $a1];
                    $resultStrArr[1] = $resultStr1;
                } elseif ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $extends[2] = [$a1, $a];
                    $resultStrArr[2] = $resultStr1;
                    //  $isdd = false;
                } elseif ($a['key'] == 'T' || $a1['key'] == 'T') {
                    $extends[3] = [$a, $a1];
                    $resultStrArr[3] = $resultStr1;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    $extends[4] = [$a1, $a];
                    $resultStrArr[4] = $resultStr1;
                    //  $isdd = false;
                } else {
                    $extends[$kke] = [$a, $a1];
                    $kke++;
                }


                $icount1++;
            }

            if ($dimensionRule == 1) {
                ksort($resultStrArr);
                $resultStr = implode($resultStrArr);
            } elseif ($dimensionRule == 2) {
                $resultStr = $highestScoreArr['key'];
            }
        }
//        halt($getDimension);
        $extends2[1] = [];
        $extends2[2] = [];
        $extends2[3] = [];
        $extends2[4] = [];
        foreach ($getDimension as $key=>$value)
        {
            if ($value['key']=='E' || $value['key']=='I'){
                array_push($extends2[1],$value);
            }
            if ($value['key']=='S' || $value['key']=='N'){
                array_push($extends2[2],$value);
            }
            if ($value['key']=='T' || $value['key']=='F'){
                array_push($extends2[3],$value);
            }
            if ($value['key']=='J' || $value['key']=='P'){
                array_push($extends2[4],$value);
            }
        }
        $resultStr = '';
        foreach ($extends2 as $key=>$value){
            if ($value[0]['score']>=$value[1]['score']){
                $resultStr .=$value[0]['key'];
            }else{
                $resultStr .=$value[1]['key'];
            }
        }
//        halt($resultStr);
        foreach ($extends1 as $k => $v) {
            foreach ($getDimension as $kk => $vv) {
                if (strstr($k, $vv['key'])) {
                    $extends1[$k] += $vv['score'];
                }
            }
        }


        $exArr = [];
        // rsort($extends1);
        foreach ($extends1 as $k => $v) {
            $exArr[] = [
                'str' => $k,
                'score' => $v,
            ];
        }
        // var_dump($exArr);die;
        $idArr = array_column($exArr, 'score');

        array_multisort($idArr, SORT_DESC, $exArr);


        $invitation_code = $model['invitation_code'];
        if ($invitation_code) {
            if ($model['status'] == "finish") {
                \think\Db::name('mental_invitationcode')->where(['invitation_code' => $invitation_code])->setInc('used_num');
            }
        }

//        halt($resultStr);
        $model->dimensionArr = json_encode($getDimension);
        $model->total_score = $totalScore;
        $model->extends  = json_encode($extends);
        $model->extends1 = json_encode($exArr);
        $model->resultStr = $resultStr;



        return $model;
    }
    
    /**
     * 卡特尔16PF性格测评计算规则
     */
    public static function getRule11($model)
    {
        $resultStr = '';
        $extends = [];
        $extends1 = [
            'A' => 0,
            'B' => 0,
            'C' => 0,
            'E' => 0,
            'F' => 0,
            'G' => 0,
            'H' => 0,
            'I' => 0,
            'L' => 0,
            'M' => 0,
            'N' => 0,
            'O' => 0,
            'Q1' => 0,
            'Q2' => 0,
            'Q3' => 0,
            'Q4' => 0,
        ];
        $result_arr = json_decode(html_entity_decode($model['result_log']), true);
        $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');

        $dimensionRule = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionRule'); //维度配置规则
        $dimensionArr = json_decode($dimensionArr);
        //去统计分数
        $testson = new Testson();
        $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);
        $totalScore = $testson->totalScore($model['main_id'], $result_arr); //统计分数
        $highestScoreArr = []; //最高分数组
        $highestScore = 0;
        // halt($getDimension);die;
        foreach ($getDimension as $k => $v) {
            $getDimension[$k]['proportion'] = round($v['score'] / $totalScore * 100, 2);

            if ($v['score'] > $highestScore) {
                $highestScoreArr = $v;
                $highestScore = $v['score'];
            }
        }

        $getDimensionCount = count($getDimension);
        $isdc = $getDimensionCount % 2;
        if ($isdc == 0) {

            $icount = $getDimensionCount / 2;
            $icount1 = $icount;
            $kke = 5;
            $resultStrArr = [];
            for ($i = 0; $i < $icount; $i++) {
                $a = $getDimension[$i];
                $a1 = $getDimension[$icount1];
                $isdd = true;
                if ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $isdd = false;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    //  $extends[4] = [$a1,$a];
//                    $resultStrArr[4] = $resultStr1;
                    $isdd = false;
                }
                if ($a['score'] > $a1['score']) {
                    $resultStr1 = $a['key'];
                    $a['large'] = true;
                    $a1['large'] = false;
                } elseif ($a['score'] == $a1['score']) {
                    if ($isdd) {
                        $resultStr1 = $a1['key'];
                        $a['large'] = false;
                        $a1['large'] = true;
                    } else {
                        $resultStr1 = $a['key'];
                        $a['large'] = true;
                        $a1['large'] = false;
                    }
                } else {
                    $resultStr1 = $a1['key'];
                    $a['large'] = false;
                    $a1['large'] = true;
                }

                if ($a['key'] == 'E' || $a1['key'] == 'E') {
                    $extends[1] = [$a, $a1];
                    $resultStrArr[1] = $resultStr1;
                } elseif ($a['key'] == 'S' || $a1['key'] == 'S') {
                    $extends[2] = [$a1, $a];
                    $resultStrArr[2] = $resultStr1;
                    //  $isdd = false;
                } elseif ($a['key'] == 'T' || $a1['key'] == 'T') {
                    $extends[3] = [$a, $a1];
                    $resultStrArr[3] = $resultStr1;
                } elseif ($a['key'] == 'J' || $a1['key'] == 'J') {
                    $extends[4] = [$a1, $a];
                    $resultStrArr[4] = $resultStr1;
                    //  $isdd = false;
                } else {
                    $extends[$kke] = [$a, $a1];
                    $kke++;
                }


                $icount1++;
            }

            if ($dimensionRule == 1) {
                ksort($resultStrArr);
                $resultStr = implode($resultStrArr);
            } elseif ($dimensionRule == 2) {
                $resultStr = $highestScoreArr['key'];
            }
        }
//        halt($getDimension);
        $extends2[1] = [];
        $extends2[2] = [];
        $extends2[3] = [];
        $extends2[4] = [];
        $extends2[5] = [];
        $extends2[6] = [];
        $extends2[7] = [];
        $extends2[8] = [];
        $extends2[9] = [];
        $extends2[10] = [];
        $extends2[11] = [];
        $extends2[12] = [];
        $extends2[13] = [];
        $extends2[14] = [];
        $extends2[15] = [];
        $extends2[16] = [];
        foreach ($getDimension as $key=>$value)
        {
            if ($value['key']=='A') array_push($extends2[1],$value);
            if ($value['key']=='B') array_push($extends2[2],$value);
            if ($value['key']=='C') array_push($extends2[3],$value);
            if ($value['key']=='E') array_push($extends2[4],$value);
            if ($value['key']=='F') array_push($extends2[5],$value);
            if ($value['key']=='G') array_push($extends2[6],$value);
            if ($value['key']=='H') array_push($extends2[7],$value);
            if ($value['key']=='I') array_push($extends2[8],$value);
            if ($value['key']=='L') array_push($extends2[9],$value);
            if ($value['key']=='M') array_push($extends2[10],$value);
            if ($value['key']=='N') array_push($extends2[11],$value);
            if ($value['key']=='O') array_push($extends2[12],$value);
            if ($value['key']=='Q1') array_push($extends2[13],$value);
            if ($value['key']=='Q2') array_push($extends2[14],$value);
            if ($value['key']=='Q3') array_push($extends2[15],$value);
            if ($value['key']=='Q4') array_push($extends2[16],$value);
        }
      
        $resultStr = '';
        foreach ($extends2 as $key=>$value){
            if($value[0]['score']>$resultStr){
                $resultStr = $value[0]['key'];
            }
        }
        foreach ($extends1 as $k => $v) {
            foreach ($getDimension as $kk => $vv) {
                if (strstr($k, $vv['key'])) {
                    $extends1[$k] += $vv['score'];
                }
            }
        }

        $exArr = [];
        // rsort($extends1);
        foreach ($extends1 as $k => $v) {
            $exArr[] = [
                'str' => $k,
                'score' => $v,
            ];
        }
        // var_dump($exArr);die;
        $idArr = array_column($exArr, 'score');

        array_multisort($idArr, SORT_DESC, $exArr);


        $invitation_code = $model['invitation_code'];
        if ($invitation_code) {
            if ($model['status'] == "finish") {
                \think\Db::name('mental_invitationcode')->where(['invitation_code' => $invitation_code])->setInc('used_num');
            }
        }


        $model->dimensionArr = json_encode($getDimension);
        $model->total_score = $totalScore;
        $model->extends  = json_encode($extends);
        $model->extends1 = json_encode($exArr);
        $model->resultStr = $resultStr;



        return $model;
    }
    /**
     * 情商规则
     */
    public static function getRule5($model)
    {
        $total_score = $model['total_score'];

        if ($total_score < 60) {
            $model->resultStr = 4;
        } elseif ($total_score >= 60 && $total_score < 90) {
            $model->resultStr = 3;
        } elseif ($total_score >= 90 && $total_score < 120) {
            $model->resultStr = 2;
        } elseif ($total_score > 120 && $total_score <= 150) {
            $model->resultStr = 1;
        }


        return $model;
    }
    /**
     * 焦虑规则
     */
    public static function getRule6($model)
    {
        $total_score = $model['total_score'];

        if ($total_score < 49) {
            $model->resultStr = 4;
        } elseif ($total_score >= 50 && $total_score < 60) {
            $model->resultStr = 3;
        } elseif ($total_score >= 60 && $total_score < 69) {
            $model->resultStr = 2;
        } elseif ($total_score > 70 && $total_score <= 80) {
            $model->resultStr = 1;
        }


        return $model;
    }
    /**
     * MIDAS多元智能规则
     */
    public static function getRule7($model)
    {
        $dimensionArr = $model['dimensionArr'];

//        if ($total_score < 49) {
//            $model->resultStr = 4;
//        } elseif ($total_score >= 50 && $total_score < 60) {
//            $model->resultStr = 3;
//        } elseif ($total_score >= 60 && $total_score < 69) {
//            $model->resultStr = 2;
//        } elseif ($total_score > 70 && $total_score <= 80) {
//            $model->resultStr = 1;
//        }
//
//
//        return $model;
    }
    /**
     * PDP性格测试
     */
    public static function getRule9($model)
    {
        $result_arr = json_decode(html_entity_decode($model['result_log']), true);
        $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');

        $dimensionArr = json_decode($dimensionArr);
        //去统计分数
        $testson = new Testson();
        $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);

        $highestScore = [
            'score'=>0,
            'key'=>'',
        ];
        foreach ($getDimension as $k => $v) {
            if ($v['score'] > $highestScore['score']) {
                $highestScore['score'] = $v['score'];
                $highestScore['key'] = $v['key'];
            }
        }
//        halt($highestScore);
        $model->resultStr = $highestScore['key'];
        return $model;
    }
    /**
     * 九型人格性格测试
     */
    public static function getRule10($model)
    {
        $result_arr = json_decode(html_entity_decode($model['result_log']), true);
        $dimensionArr = \think\Db::name('mental_testmain')->where('id', $model['main_id'])->value('dimensionArr');

        $dimensionArr = json_decode($dimensionArr);
        //去统计分数
        $testson = new Testson();
        $getDimension = $testson->getDimension($model['main_id'], $result_arr, $dimensionArr);

        $highestScore = [
            'score'=>0,
            'key'=>'',
        ];
        foreach ($getDimension as $k => $v) {
            if ($v['score'] > $highestScore['score']) {
                $highestScore['score'] = $v['score'];
                $highestScore['key'] = $v['key'];
            }
        }
//        halt($highestScore);
        $model->resultStr = $highestScore['key'];
        return $model;
    }

    /**
     * 年龄折算分规则
     */
    public static function getRule1($model)
    {
        $total_score = $model['total_score'];
        $age = $model['age'];

        if ($age == "5-10") {
            $total_score = $total_score * 5;
        } elseif ($age == "10-15") {
            $total_score = $total_score * 4;
        } elseif ($age == "15-20") {
            $total_score = $total_score * 3;
        } elseif ($age == "20-25") {
            $total_score = $total_score * 2;
        } elseif ($age == "25-30") {
            $total_score = $total_score * 2;
        } elseif ($age == "30-40") {
            $total_score = $total_score * 2;
        } elseif ($age == "40-50") {
            $total_score = $total_score * 2;
        } elseif ($age == "50-60") {
            $total_score = $total_score * 2;
        } elseif ($age == "60-70") {
            $total_score = $total_score * 2;
        }

        $model->total_score = $total_score;


        if ($total_score < 20) {
            $model->resultStr = 5;
        } elseif ($total_score >= 20 && $total_score < 60) {
            $model->resultStr = 4;
        } elseif ($total_score >= 60 && $total_score < 80) {
            $model->resultStr = 3;
        } elseif ($total_score >= 80 && $total_score < 100) {
            $model->resultStr = 2;
        } elseif ($total_score >= 100) {
            $model->resultStr = 1;
        }


        return $model;
    }





    public function getEvaluationStructureAttr()
    {
        return config('site.evaluationStructure');
    }

    public function getTestreportData2Attr($value, $data)
    {
        $mt = \think\Db::name('mental_testreport')->where(['main_id' => $data['main_id'], 'dimensionConfig' => $data['resultStr']])->find();

        $arr = [];
        if ($mt) {
            for ($i = 0; $i < 14; $i++) {
                $image = '';
                $imageTitle = '';
                if ($i == 0) {
                    $i = '';
                } elseif ($i == 1) {
                    $image = $mt['image'];
                    $imageTitle = $mt['imageTitle'];
                }
                if ($mt['content' . $i]) {
                    $arr[] = [
                        'title' => $mt['title' . $i],
                        'tag' => $mt['tag' . $i],
                        'colour' => $mt['colour' . $i],
                        'content' => $mt['content' . $i],
                        'image' => $image,
                        'imageTitle' => $imageTitle,
                    ];
                }
            }
        }


        return $arr;
    }


    public function getImgarrAttr($value, $data)
    {
        $mt = \think\Db::name('mental_testreport')->where(['main_id' => $data['main_id'], 'dimensionConfig' => $data['resultStr']])->field('image,imageTitle')->find();

        return $mt;
    }


    public function getTestreportData1Attr($value, $data)
    {

        
        $mt = \think\Db::name('mental_testreport')->where(['main_id' => $data['main_id'], 'dimensionConfig' => $data['resultStr']])->field('dimensionImageConfig,version')->find();
        if ($mt) {
            $arr = json_decode($mt['dimensionImageConfig'], true);

            for ($i = 1; $i < 5; $i++) {
                $isKey = array_key_exists($i, $arr);
                if (!$isKey) {
                    $arr[$i] = false;
                }
            }
            $mt['dimensionImageConfig'] = $arr;
        }
    


        return $mt;
    }

    // public static function update111($data)
    // {


    //     return $getDimension;
    // }

    // 获取维度
    public function getDimensionArrAttr($value, $data)
    {
        // var_dump($data);die;
        $arr = json_decode($value, true);
        $ret = [];
        foreach ($arr as $v) {
            $ret[] = $v;
        }


        return $ret;
    }

    public function getExtendsAttr($value, $data)
    {
        return $value ? json_decode($value, true) : [];
    }

    public function getExtends1Attr($value, $data)
    {
        return $value ? json_decode($value, true) : [];
    }
    public function getStatusList()
    {
        return ['unfinishu' => __('Status unfinishu'), 'finish' => __('Status finish')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function detail($id, $user_id)
    {

        $where = [
            'id' => $id,
        ];

        if ($user_id !== 0) {
            $where['user_id'] = $user_id;
        }

        return $this->with('Test')
            ->field('id,user_id,main_id,title,content,type,status,testNo,updatetime,createtime,result_log,dimensionArr,total_score,extends,extends1,resultStr,full_name,position,age,gender,invitation_code,phone')
            ->where($where)
            ->find();
    }

    /**
     * Undocumented function
     * 列表
     * @return Object
     */
    public function tableList($param)
    {
        $limit = 10;
        if (isset($param['limit'])) {
            $limit = $param['limit'];
        }
        $whereArr = $this->tableWhere($param);
//        var_dump($whereArr);
        return $this->with('myTest')->field($whereArr['field'])->where($whereArr['where'])->order($whereArr['order'])->paginate($limit);
    }

    /**
     * 获取做题时间
     */
    public function getQuestionTimeAttr($value, $data)
    {
        $ret = '无';
        if ($data['updatetime']) {
            $min = $data['updatetime'] - $data['createtime'];
            $ret = $min / 60;
        }

        return $ret;
    }

    /**
     * Undocumented function
     * 统一处理查询条件
     * @param [type] $param
     * @return void
     */
    public function tableWhere($param)
    {
        $where = [];
        if (isset($param['user_id']) && !empty($param['user_id'])) {
            $where['user_id'] = $param['user_id'];
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $where['status'] = $param['status'];
        }
        $result['where'] = $where;
        $result['field'] = "id,user_id,main_id,status,createtime,updatetime,resultStr";
        $result['order'] = ['id desc'];
        return $result;
    }

    public function Test()
    {
        return $this->hasOne('TestMain', 'id', 'main_id')->bind(['test_title' => 'title', 'test_num', 'image', 'pay_mode', 'rotationImg', 'template']);
    }

    public function myTest()
    {
        return $this->hasOne('TestMain', 'id', 'main_id')->bind(['title', 'test_num', 'description', 'price', 'image']);
    }
}
